package utils;

import java.awt.*;
import java.awt.image.BufferedImage;
import java.util.Random;

public class ValidateCodeWithImage {
    private static final int width = 60;
    private static final int height = 25;
    private static final String allChar = "abcdefghigklmnopqrstuvwxyz0123456789ABCDEFGHIGKLMNOPQRSTUVWXYZ";

    public BufferedImage getBufferedImage(){
        BufferedImage bufferedImage = new BufferedImage(width,height,BufferedImage.TYPE_INT_RGB);

        Graphics graphics = bufferedImage.getGraphics();

        //画背景
        Color bgColor = getColor();
        graphics.setColor(bgColor);
        graphics.fillRect(0,0,width,height);

        //填充验证码
        graphics.setColor(getColor(bgColor));
        graphics.drawString(getCode(5),5,20);
        //画验证码
        return bufferedImage;
    }

    private Color getColor(){
        Random random = new Random();
        int r = random.nextInt(256);
        int g = random.nextInt(256);
        int b = random.nextInt(256);
        return new Color(r,g,b);
    }
    private Color getColor(Color oppositeColor){
        int r = 255 - oppositeColor.getRed();
        int g = 255 - oppositeColor.getGreen();
        int b = 255 - oppositeColor.getBlue();
        return new Color(r,g,b);
    }

    private String getCode(int len){
        Random random = new Random();
        StringBuffer stringBuffer = new StringBuffer();
        int round = allChar.length();
        for (int i = 0; i < len; i++) {
            char c = allChar.charAt(random.nextInt(round));
            stringBuffer.append(c);
        }
        return stringBuffer.toString();
    }
}
